#!/usr/bin/python
import os, sys, time, json, beanstalkc

def main():
    abspath = os.path.abspath(os.path.dirname(__file__))
    rev_ref_arr = []
    max_line_count = 50
    for line in sys.stdin.xreadlines():
        max_line_count = max_line_count - 1
        if max_line_count < 0:
            break
        rev_ref_arr.append(line.strip().split(' ')) 
    remote_user = get_remote_user()
    json_map = {}
    json_map['type'] = 0
    json_map['remote_user'] = remote_user
    json_map['push_timestamp'] = long(time.time())
    json_map['abspath'] = abspath
    json_map['revrefarr'] = rev_ref_arr
    event = json.dumps(json_map)
    send_commit_event(event)

def get_remote_user():
    if 'REMOTE_USER' in os.environ:
        return os.environ['REMOTE_USER']
    return ''

def switch(beanstalk, tube):
    beanstalk.use(tube)
    beanstalk.watch(tube)
    beanstalk.ignore('default')

def send_commit_event(event):
    beanstalk = beanstalkc.Connection(host='localhost', port=11300)
    switch(beanstalk, 'commit_event')
    beanstalk.put(event) 

if __name__ == '__main__':
    main()

